package vanhoc.android.mediakool;

import java.util.ArrayList;
import java.util.HashMap;

import vanhoc.android.mediakool.R;
import vanhoc.android.mediakool.custom.adapter.DashboardGridAdpater;
import vanhoc.android.mediakool.db.DatabaseHelper;
import vanhoc.android.medialcool.helper.MediaPlayerHelper;
import vanhoc.android.medialcool.item.data.DashboardItemData;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

/**
 * @author Administrator
 * Khi chuong trinh chay -> chay Activity nay dau tien
 * Tai Activity nay khoi dong 1 service, Service do lay ve danh sach cac bai hat (mp3) trong /sdcard/(thong qua 1 Lop MediaPlayerHelper) 
 *  roi ket noi toi database de insert du lieu vao db thong qua DatabaseHelper class
 */

public class DashboardActivity extends Activity implements OnItemClickListener {
	
	private GridView gridDashboard;
	
	private ArrayList<DashboardItemData> arrListItemData;
	
	
	MediaPlayerHelper mediaHelper = new MediaPlayerHelper();
	
	DatabaseHelper databaseHelper = new DatabaseHelper(this);
	 
	private static final String MEDIA_PATH = "/mnt/sdcard/";
	
	ArrayList<HashMap<String, String>> arrListSong;
	
	ArrayList<HashMap<String, String>> arrListVideos;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        
     // init dashboard
        initDashboardView();
        
        //Kiem tra xem da ton tai database trong ung dung chua
    	if (checkExistDatabase()) {
    		//updateSongTable();
		}else{
			new getDataTask().execute();
		}
    }
    
    
    
    /**
     * Initt Dashboard 
     */
    private void initDashboardView(){
    	gridDashboard = (GridView) findViewById(R.id.gridDashboard);
    	
    	arrListItemData = new ArrayList<DashboardItemData>();
    	arrListItemData.add(new DashboardItemData(R.drawable.song_64_icon, "Songs"));
    	arrListItemData.add(new DashboardItemData(R.drawable.album_64_icon, "ALbums"));
    	arrListItemData.add(new DashboardItemData(R.drawable.artist_64_icon, "Artists"));
    	arrListItemData.add(new DashboardItemData(R.drawable.genre_64_icon, "Genres"));
    	arrListItemData.add(new DashboardItemData(R.drawable.playlist_64_icon, "Playlist"));
    	arrListItemData.add(new DashboardItemData(R.drawable.video_64_icon, "Video"));
    	
    	 //init  Adapter for Dashboard
        DashboardGridAdpater gvDashboardAdapter = new DashboardGridAdpater(this, R.id.gridDashboard, arrListItemData);
        gridDashboard.setAdapter(gvDashboardAdapter);
        
    	gridDashboard.setOnItemClickListener(this);
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		Intent it = new Intent(getApplicationContext(), TabControlActivity.class);
		it.putExtra("tab", position);
    	startActivity(it);
	}
	
	
	@Override
	public void onBackPressed() {
		//super.onBackPressed();
		finish();
		System.exit(0);
	}
	
	/**
     * Check the exist of database of app
     * @return
     */
    private boolean checkExistDatabase() {
	    SQLiteDatabase checkDB = null;
	    try {
	        checkDB = SQLiteDatabase.openDatabase("/data/data/vanhoc.android.mediakool/databases/mediaplayer.db", null,
	                SQLiteDatabase.OPEN_READONLY);
	        checkDB.close();
	    } catch (SQLiteException e) {
	        // database doesn't exist yet.
	    }
	    return checkDB != null ? true : false;
	}
    
    
    /**
     * Update songs Table in database
     */
    public void updateSongTable(){
    	//Neu nhu da co thi lay ve tat cac file .mp3 trong the nho (/mnt/sdcard/) trong 1 Arraylist
		//Duyet qua tung file .mp3 trong ArrayList do roi kiem tra xem trong database da co chua.Neu co roi thi thoi.Neu chua co thi insert vo db chi nhung file .mp3 chua co thoi
    	DatabaseHelper databaseHelper = new DatabaseHelper(DashboardActivity.this);
    	databaseHelper.openToWrite();
		for (int i = 0; i < arrListSong.size(); i++) {
			if (!checkExistSongDB(arrListSong.get(i).get("name"))) {
				//Insert bai hat chua dc luu vao trong db
				databaseHelper.insertSong(arrListSong.get(i));
			}
		}
		databaseHelper.close();
    }
    
    /**
     * Phuong thuc kiem tra xem 1 song da dc luu tru trong db hay chua
     * @param songName : Ten cua bai hat can kiem tra
     * @return True : neu da ton tai, False neu chua
     */
    public Boolean checkExistSongDB(String songName){
    	Boolean check = false;
    	//Lay ve danh sach ten cac bai hat da dc luu trong db
    	ArrayList<String> arrListSongSaved = getLAllSongFromDB();
    	for (int i = 0; i < arrListSongSaved.size(); i++) {
			if (arrListSongSaved.get(i).equals(songName)) {
				check = true;
			}
		}
    	
    	return check;
    }
    
  //Insert list song to Videos table 
    private void insertListVideosToDB() {
    	databaseHelper.openToWrite();
    	for (int i = 0; i < this.arrListVideos.size(); i++) {
    		databaseHelper.insertVideo(this.arrListVideos.get(i));
		}
    	databaseHelper.close();
	}


	/**
     * Insert list song to Songs table 
     */
    public void insertListSongToDB(){
    	databaseHelper.openToWrite();
    	//databaseHelper.deleteAllSong();
    	for (int i = 0; i < arrListSong.size(); i++) {
			databaseHelper.insertSong(arrListSong.get(i));
		}
    	databaseHelper.close();
    }
    
    /**
     * Lay ve ten cua tat ca cac bai hat dc luu trong database
     * @return
     */
    public ArrayList<String> getLAllSongFromDB(){
    	ArrayList<String> listSong = new ArrayList<String>();
    	//Thao tac voi csdl de lay ve danh sach ten cac bai hat da dc inserted vo db
    	DatabaseHelper databaseHelper = new DatabaseHelper(DashboardActivity.this);
    	databaseHelper.openToRead();
    	Cursor cursor = databaseHelper.getSingleInfoAllSong("name");
    	startManagingCursor(cursor);
    	
    	cursor.moveToFirst();
    	for (int i = 0; i < cursor.getCount(); i++) {
    		listSong.add(cursor.getString(0));
    		cursor.moveToNext();
		}
    	//close database
    	databaseHelper.close();
    	
    	return listSong;
    }
    
    
    public class getDataTask extends AsyncTask<Void, Void, Void>
    {
    	
		private ProgressDialog dialog;
 	   @Override
 	   protected void onPreExecute() {
 		   // TODO Auto-generated method stub
 		   super.onPreExecute();
 		   
 		   dialog = ProgressDialog.show(DashboardActivity.this, "", "Scanning sdcard...");
 	   }
 	   
 	   @Override
 	   protected Void doInBackground(Void... params) {
 		   // TODO Auto-generated method stub
 		  //Lay ve tat ca cac file .mp3 trong the nho
		 	arrListSong = (ArrayList<HashMap<String, String>>) mediaHelper.getAllSongFromSdCard(MEDIA_PATH);
		    
		 	//Lay ve danh sach tat ca cac dinh dang video : mp4, 3gp,wav...
		 	arrListVideos	=	mediaHelper.getAllVideoFromSdCard(MEDIA_PATH);
		 	
			
 		   return null;
 	   }
 	   
 	   @Override
 	   protected void onPostExecute(Void result) {
 		   // TODO Auto-generated method stub
 		   super.onPostExecute(result);
 		   
 		   if(dialog.isShowing())
 		   {
 			   dialog.dismiss();
 		   }
 		   
 		 //Neu chua co db --> lan chay dau tien
		//Insert du lieu vao database
        insertListSongToDB();
        insertListVideosToDB();
 	   }
    }

}
